import sys
import yaml
import urllib.request 
from http import client
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QSizePolicy, QWidget, QLabel
from PySide6.QtCore import QRect
from PySide6.QtGui import QFont

class UpdatePromptDialod(QMainWindow):
    def __init__(self):
        super().__init__()
        self.need_update = False
        
        # window
        self.setWindowTitle("Обновление")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.resize(420,100)
        self.setSizePolicy(sizePolicy)
        self.centralwidget = QWidget(self)
        
        # label
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(10, 10, 400, 30))
        font = QFont()
        font.setPointSize(12)
        self.label.setFont(font)
        self.label.setText("Доступно обновление продукта. Скачать обновление?")
        
        # ok button
        self.okButton = QPushButton(self.centralwidget)
        self.okButton.setGeometry(QRect(90, 50, 75, 24))
        self.okButton.setText("Ok")
        self.okButton.clicked.connect(self.ok_button_clicked)
        
        # cancel buttton
        self.cancelButton = QPushButton(self.centralwidget)
        self.cancelButton.setGeometry(QRect(220, 50, 75, 24))
        self.cancelButton.setText("Cancel")        
        self.cancelButton.clicked.connect(self.cancel_button_clicked)
        
        self.setCentralWidget(self.centralwidget)
        
    def ok_button_clicked(self, s):
        self.need_update = True 
        self.close() 
    def cancel_button_clicked(self, s):
        self.need_update = False 
        self.close()         

class VersionChecker(object):
    
    def __init__(self,metadata:dict={}):
        self.metadata = metadata
        self.current_version = metadata.get("Version","0.0.0.0")
        self.update_version = "0.0.0.0"
        self.repo_root_url = metadata.get("Repo",None)
        self.distr_url = f"{self.repo_root_url}/dummy.zip"
    @staticmethod
    def get_int_version(str_version:str)->int:
        try:
            ver = int(str_version.replace(".",""))
            return ver
        except: return -1
        
    def update_exists(self)->bool:
        try:
            if self.repo_root_url is None: raise Exception("Отсутствует url репозитория для проверки обновлений.")
            try:
                response:client.HTTPResponse = urllib.request.urlopen(f"{self.repo_root_url}/metadata.yml")
            except: return False
            if response.status!=200: return False
            data = response.read()
            update_metadata:dict = yaml.load(data, Loader=yaml.FullLoader)
            self.update_version = update_metadata.get("Version","0.0.0.0")
            product = self.metadata.get("ProductName","dummy")
            self.distr_url = f"{self.repo_root_url}/{product}-v.{self.update_version}.zip"
            update_ver_int = VersionChecker.get_int_version(self.update_version)
            cur_ver_int = VersionChecker.get_int_version(self.current_version)
            return update_ver_int > cur_ver_int
        except: raise
        
    def show_update_dialog(self)->bool:
        try:
            app = QApplication(sys.argv)
            app.setStyle("Windows")
            win = UpdatePromptDialod()
            win.show()
            res=app.exec()
            return win.need_update
        except : raise